package com.mediacloud.app.newsmodule.activity.microlive.x

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.mediacloud.app.newsmodule.R
import com.mediacloud.im.sdk.TXImManager
import com.tencent.imsdk.*
import com.tencent.qcloud.tim.uikit.modules.chat.GroupChatManagerKit
import com.tencent.qcloud.tim.uikit.modules.message.MessageInfo
import com.tencent.qcloud.tim.uikit.modules.message.MessageInfoUtil
import kotlinx.android.synthetic.main.x_microlive_im_comment_fragment.*

class IMCommentFragment : Fragment(), TIMMessageListener {
    private var articleTitle: String? = null
    var roomId: String? = null
    var conversation: TIMConversation? = null
    var adapter: IMCommentAdapter? = null
    var mConversation: TIMConversation? = null
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        articleTitle = arguments?.getString("ARTICLE_TITLE")
        roomId = arguments?.getString("ROOM_ID")
        return inflater.inflate(R.layout.x_microlive_im_comment_fragment, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mRecyclerView.layoutManager = LinearLayoutManager(requireContext())
        adapter = IMCommentAdapter(requireContext())
        adapter?.data?.add(IMCommentData("$articleTitle", "欢迎来到直播间，直播间提倡健康的直播环境，对直播内容24小时巡查，任何传播违法、违规、低俗等不良信息时即将被封号。"))
        mRecyclerView.adapter = adapter
        if (TXImManager.getInstance().isLogin) {
            initIm()
            conversation = TIMManager.getInstance().getConversation(TIMConversationType.Group, roomId)
        }
    }

    override fun onNewMessages(p0: MutableList<TIMMessage>?): Boolean {
        if (activity==null||requireActivity().isFinishing||requireActivity().isDestroyed){
            return false
        }
        p0?.forEach {
            if (it.conversation.peer == TIMManager.getInstance().getConversation(TIMConversationType.Group, "$roomId").peer) {
                for (i in 0 until it.elementCount) {
                    val elem = it.getElement(i)
                    if (elem is TIMTextElem) {
                        val nick = if (it.senderNickname?.isNotEmpty()==true) {
                            it.senderNickname
                        } else {
                            "匿名用户"
                        }
                        val item = IMCommentData(nick, elem.text)
                        adapter?.data?.add(item)
                        adapter?.notifyDataSetChanged()
                    }
                }

            }
        }
        return false
    }


    private fun initIm() {
        TIMGroupManager.getInstance().applyJoinGroup("$roomId", "", object : TIMCallBack {
            override fun onSuccess() {
                if (activity==null||requireActivity().isFinishing||requireActivity().isDestroyed){
                    return
                }
                Log.e("YOAKE", "加群 onSuccess")
            }

            override fun onError(p0: Int, p1: String?) {
                if (activity==null||requireActivity().isFinishing||requireActivity().isDestroyed){
                    return
                }
                Log.e("YOAKE", "加群 onError$p1")
                val param = TIMGroupManager.CreateGroupParam("AVChatRoom", "$articleTitle")
                param.groupId = "$roomId"
                TIMGroupManager.getInstance().createGroup(param, object : TIMValueCallBack<String> {
                    override fun onSuccess(p0: String?) {
                        if (activity==null||requireActivity().isFinishing||requireActivity().isDestroyed){
                            return
                        }
                        Log.e("YOAKE", "创群 onSuccess")
                    }

                    override fun onError(p0: Int, p1: String?) {
                        if (activity==null||requireActivity().isFinishing||requireActivity().isDestroyed){
                            return
                        }
                        Log.e("YOAKE", "创群 onError$p1")
                    }
                })
            }
        })
        TIMManager.getInstance().addMessageListener(this)
    }

    fun setMessage(content: String) {
        val item = IMCommentData(TIMFriendshipManager.getInstance().querySelfProfile().nickName, content)
        adapter?.data?.add(item)
        adapter?.notifyDataSetChanged()
        val msg = MessageInfoUtil.buildTextMessage(content);
        sendGroupTips("$roomId", msg)
    }

    private fun sendGroupTips(chatId: String, message: MessageInfo) {
        if (mConversation == null)
            mConversation = TIMManager.getInstance().getConversation(TIMConversationType.Group, chatId)

        mConversation?.sendMessage(message.timMessage, object : TIMValueCallBack<TIMMessage> {
            override fun onSuccess(p0: TIMMessage?) {
                if (activity==null||requireActivity().isFinishing||requireActivity().isDestroyed){
                    return
                }
                Log.e("MessageSender", "onSuccess = $chatId  ${p0?.getElement(0)}")
                val msgs = ArrayList<TIMMessage>()
                msgs.add(message.timMessage)
                GroupChatManagerKit.getInstance().onNewMessages(msgs)
            }

            override fun onError(p0: Int, p1: String?) {
                if (activity==null||requireActivity().isFinishing||requireActivity().isDestroyed){
                    return
                }
                Log.e("MessageSender", "onError = $chatId")
                val msgs = ArrayList<TIMMessage>()
                msgs.add(message.timMessage)
                GroupChatManagerKit.getInstance().onNewMessages(msgs)
            }
        })

    }

    override fun onDestroy() {
        super.onDestroy()
        TIMManager.getInstance().removeMessageListener(this)
    }
}



